package cn.cdyx.common.utils;

import cn.cdyx.common.pojo.Code;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @Author Watermelon
 * @Date 2023-01-17 11:07
 * 接口加密注册 此处使用AES-128-ECB加密模式，秘钥统一再Code中配置
 */
public class SecuritUtil {

    /**
     *  加密
     * @param sSrc 明文
     * @param sKey 秘钥
     * @return
     * @throws Exception
     */
    public static String encrypt(String sSrc,String sKey) throws Exception {

        if (sKey == null) {
            throw new Exception("加密密钥不能为空");
        }
        /*if (!sKey.equals(Code.SYSTEM_INTERFACE_KEY)) {
            throw new Exception("秘钥错误");  方便每个接口单独注册  不进行判断
        }*/
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// "算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));

        return new Base64().encodeToString(encrypted);// 此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }


    /** AES解密
     * @param sSrc 密文
     * @param sKey 加密密钥
     * @return 明文
     * @throws Exception 异常信息
     */
    public static String decrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null) {
            throw new Exception("加密密钥为null");
        }
        /*if (!sKey.equals(Code.SYSTEM_INTERFACE_KEY)) {
            throw new Exception("秘钥错误");
        }*/
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);

        byte[] encrypted1 = new byte[0];// 先用base64解密
        try {
            encrypted1 = new Base64().decode(sSrc);
        } catch (Exception e) {
            throw new RuntimeException("接口注册码错误！");
        }
        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original, "utf-8");
        return originalString;
    }

}